import { createRouter, createWebHashHistory } from 'vue-router'
import LoginView from '../views/LoginView.vue'
import LayoutView from '../views/LayoutView.vue'
import WelCome from '../views/home/WelComeView.vue'

import { getResources } from '../api/auth'
const routes = [
   {
    path: '/login',
    name: 'login',
    component: LoginView
  },{
    path:'/',
    name:'首页',
    component:LayoutView,
    redirect: '/home',
    children:[
      {
        path:'/home',
        name:'欢迎页',
        component:WelCome
      },
      {
        path:'/system',
        name:"系统管理",
        mete:{title:"系统管理"},
        children:[
          {
            path:'/system/user',
            name:'用户管理',
            meta:{title:"用户管理"},
            component:()=>import("../views/system/UserView.vue")
          },{
            path:'/system/role',
            name:'角色管理',
            meta:{title:"角色管理"},
            component:()=>import("../views/system/RoleView.vue")
          },{
            path:'/system/permission',
            name:'权限管理',
            meta:{title:"权限管理"},
            component:()=>import("../views/system/PermissionView.vue")
          }
        ]
      },{
        path:"/userInfo",
         name:'用户信息查看',
         component:()=> import("../views/user/UserInfoView.vue")
      }
    ]
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})


// 路由守卫
router.beforeEach(async (to, from, next) => {
  const token =  localStorage.getItem('token') // 获取 token
  const isLogin = !!token // 判断是否已登录

  if (to.path === '/login') {
    // 访问的是登录页
    if (isLogin) {
      // 已登录，跳转首页
      next('/')
    } else {
      // 未登录，直接放行
      next()
    }
  } else {
    // 访问的是非登录页
    if (isLogin) {

      // 动态导入并使用 store
      const { useUserInfoStore } = await import('../store/index')
      const userStore = useUserInfoStore()
      if( !(userStore.nav && userStore.nav.length > 0) ){
        let res = await getResources()
        // 将数据放入到pinia中
        // 保存菜单
        userStore.setNav(res.data.menus)
        // 保存权限集合
        userStore.setPermission(res.data.permissions)
       
      }
      // 已登录，放行
      next()
    } else {
      // 未登录，跳转登录页
      next('/login')
    }
  }
})


export default router